package com.example.fund.util;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.example.fund.updatestategy.FundNetValueUpdateStrategy;
import com.example.fund.updatestategy.UpdateStrategy;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class FundUtil2 {

	private final static DateFormat DF1 = new SimpleDateFormat("yyyy-MM-dd");
	private static Map<String,Map<String,Double>> indexNetValue = new HashMap<String,Map<String,Double>>();
	/**
	 * 计算基金与各指数的相关系数
	 * @param
	 * @param fundNumber
	 * @return
	 */
	public static List<Map.Entry<String,Double>> getStdev(String fundNumber)
	{
		Map<String,Double> map = new HashMap<String,Double>();
		
//        String lastDate = FundUtil.getFundLastDate(fundNumber);
//        String shLastDate = FundUtil.getFundLastDate("0000001");
  //      FundUtil.getFundNetValueFromUrl(fundNumber,lastDate,shLastDate);
		UpdateStrategy updateStrategy = new FundNetValueUpdateStrategy(fundNumber);
		updateStrategy.updateIndex();
		Map<String,Double> fundNetValueMap = getFundPeriodNetValue(fundNumber);
		
		List<String> dateList = FundUtil.getSHIndexDateList();
		Map<String,Double> shNetValueMap = getFundPeriodNetValue("0000001");
		
		Map<String,Map<String,Double>> indexNetValue = getIndexNetValue();
		for(String number:indexNetValue.keySet())
		{
			if("0000000".equals(number))
			{
				continue;
			}
			Double beginValue0 = null;
			Double beginValue1 = null;//起始实际净值
			Double beginValue2 = null;//起始实际净值
			Map<String,Double> indexNetValueMap = indexNetValue.get(number);
			List<Double> ratioList = new LinkedList<Double>();
			for(int i=dateList.size()-1;i>=0;i--)
			{
				String dateStr = dateList.get(i);

				Double actValue1 = indexNetValueMap.get(dateStr);
				Double actValue2 = fundNetValueMap.get(dateStr);
				if(actValue1!=null && actValue2!=null && actValue1>0 && actValue2>0)
				{
					if(beginValue0==null)
					{
						beginValue0 = shNetValueMap.get(dateStr);
						if(beginValue0==null)
						{
							continue;
						}
						beginValue1 = actValue1;
						beginValue2 = actValue2;
					}
					Double value1 = beginValue0*actValue1/beginValue1;
					Double value2 = beginValue0*actValue2/beginValue2;
					Double ratio = value2/value1;
					ratioList.add(ratio);
				}
			}
			double stdev = MathUtil.stdev(ratioList);
			map.put(number, new BigDecimal(stdev).setScale(4, RoundingMode.HALF_UP).doubleValue());
		}
		//通过ArrayList构造函数把map.entrySet()转换成list
		List<Map.Entry<String,Double>> mappingList = new ArrayList<Map.Entry<String,Double>>(map.entrySet());
		//通过比较器实现比较排序 
		Collections.sort(mappingList, new Comparator<Map.Entry<String,Double>>(){ 
			public int compare(Map.Entry<String,Double> mapping1,Map.Entry<String,Double> mapping2){ 
				return mapping1.getValue().compareTo(mapping2.getValue()); 
			} 
		}); 
		
		return mappingList;
	}
	
	/**
	 * 
	 * @param
	 * @return
	 */
	public static Map<String,Map<String,Double>> getIndexNetValue()
	{
		if(indexNetValue.size()!=0)
		{
			return indexNetValue;
		}
		List<Map<String,Object>> indexList = FundUtil1.getIndexSet();
	//	for(int i=0;i<Constant.indexNumbers.length;i++)
		for(int i=0;i<indexList.size();i++)
		{
			Map<String, Object> map = indexList.get(i);
			Object numberObj = map.get("number");
			if(numberObj==null || numberObj.toString().trim().length()==0)
			{
				continue;
			}
			String number = numberObj.toString().trim();
			Map<String,Double> newValue = getFundPeriodNetValue(number);
			indexNetValue.put(number, newValue);
		}
		return indexNetValue;
	}
	
	/**
	 * 
	 * @param number
	 */
	public static Map<String,Double> getFundPeriodNetValue(String number)
	{
		Map<String,Double> netValueMap = new HashMap<String,Double>();
		
		Calendar c = Calendar.getInstance();
//		c.add(Calendar.MONTH, -6);
		c.add(Calendar.YEAR, -3);
		String date = DF1.format(c.getTime());
		
		String minDate = FundUtil.getFundMinDate(number);
		if(minDate!=null && minDate.trim().length()>0)
		{
			Calendar c1 = Calendar.getInstance();
			try {
				c1.setTime(DF1.parse(minDate));
				c1.add(Calendar.MONTH, 3);
				minDate = DF1.format(c1.getTime());
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		
//		String sql = "select date,netValue from FundNetValue where fundNumber='"+number+"' and date>='"+date+"' and date>='"+minDate+"' order by date desc";
		StringBuffer sql = new StringBuffer();
		sql.append(" select 	\n");
		sql.append("	date,	\n");
		sql.append("	netValue 	\n");
		sql.append(" from FundNetValue 	\n");
		sql.append(" where fundNumber='"+number+"' 	\n");
		sql.append(" and date>='"+date+"' 	\n");
		if(!StringUtil.isNullOrEmpty(minDate))
		{
			sql.append(" and date>='"+minDate+"' 	\n");
		}
		sql.append(" order by date desc			\n");
		
		SQLiteDatabase db = DBManager.getDB();
		Cursor cs = db.rawQuery(sql.toString(), null);
		while (cs.moveToNext())
		{
			String dateStr = cs.getString(cs.getColumnIndex("date"));
            double netValue = cs.getDouble(cs.getColumnIndex("netValue"));
            if(StringUtil.isNullOrEmpty(dateStr))
            {
            	continue;
            }
            netValueMap.put(dateStr, netValue);
		}
		cs.close();
		
		return netValueMap;
	}
}
